// pages/route1/c_seat/c_seat.js
const app = getApp()
var rest = 0;
var getDataFlag = false
Page({
  /**
   * 页面的初始数据
   */
  data: {
    count: 1,
    selnum: null,
    name: '',
    phone: '',
    seat: [{
      text: 'A席位',
      price: '111',
    },
    {
      text: 'B席位',
      price: '112',
    },
    {
      text: 'C席位',
      price: '113',
    },
    {
      text: 'D席位',
      price: '114',
    },
    {
      text: 'E席位',
      price: '115',
    },
    {
      text: 'F席位',
      price: '116',
    }],
    price: 0,
    productId: '',
    orderId: '',
    checked: false,
    addresrc: {
      src1: '../image/redu.png',
      src2: '../image/add.png'
    }
  },
  _count: function (event) {
    console.log(event.currentTarget.dataset.num)
    if (event.currentTarget.dataset.num==1){
      this.setData({
        addresrc: {
          src1: '../image/redu.png',
          src2: '../image/add2.png'
        }
      })
    }
    else{
      this.setData({
        addresrc: {
          src1: '../image/redu2.png',
          src2: '../image/add.png'
        }
      })
    }
    var num = this.data.count + parseInt(event.currentTarget.dataset.num)
    console.log(this.data.seat[this.data.selnum].sellQty)
    if (num > this.data.seat[this.data.selnum].sellQty)

  {
      this.setData({
        count: this.data.seat[this.data.selnum].sellQty
      })
      return;
  }
    this.setData({
      count: num > 0 ? num : 0
    })
  },
  selseat: function (e) {
    if (this.data.seat[e.target.dataset.selnum].sellQty == 0)
      return;
    this.setData({
      selnum: e.target.dataset.selnum,
      price: this.data.seat[e.target.dataset.selnum].sellPrice
    })
  },
  bindKeyname: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindKeyphone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  submit: function () {

    var that = this;
    console.log("this.data.selnum" + this.data.selnum)
    if (this.data.selnum == undefined){
      wx.showToast({
        title: '未选择任何座位!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
    let name = this.data.name;
    let phone = this.data.phone;
    let count = this.data.count;
    let productId = this.data.productId;
    let sectionId = this.data.seat[this.data.selnum].sectionId.toString();
    let isAuto = this.data.checked == true ? 1 : 0;
    // if(rest==1){
    //   venueId=''
    // }
    if (name == '' || phone == '') {
      wx.showToast({
        title: '未输入姓名或手机号!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (mobileReg.test(phone)==false){
      wx.showToast({
        title: '手机号格式不正确!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (getDataFlag) {

      return;

    }
    getDataFlag = true;
    var session = wx.getStorageSync('session')
    var refId = wx.getStorageSync('refId')
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      url: app.globalData.rootUrl + '/api/order/create/',
      method: "POST",
      data: {
        isAuto: isAuto,
        productId: productId,
        sectionId: sectionId,
        num: count,
        name: name,
        mobile: phone,
        session: session,
        refId: refId
      },
      success: function (res) {
        if (res.data.status == 200) {
          that.setData({
            orderId: res.data.data[0]
          })
          wx.getStorage({
            key: 'openid',
            success: function (res2) {
              console.log(res2)
              wx.request({
                header: {
                  'content-type': 'application/x-www-form-urlencoded' // 默认值
                },
                url: app.globalData.rootUrl + '/wx/check',
                method: "POST",
                data: {
                  orderId: res.data.data[0],
                  openid: res2.data
                },
                success: function (res3) {
                  console.log('productId' + productId)
                  // wx.navigateTo({
                  //   url: '../buy_suc/buy_suc?session=' + session + '&productId=' + productId+ '&orderId=' + res.data.data[0],
                  // })
                  // return;
                  
                  if (res3.data.status == 200) {
                    console.log("后台用户会话", res3.data.data[0])
                    let pay = res3.data.data[0]
                    wx.requestPayment({
                      'timeStamp': pay.timeStamp.toString(),
                      'nonceStr': pay.nonceStr,
                      'package': pay.package,
                      'signType': 'MD5',
                      'paySign': pay.sign,
                      'success': function (res4) {
                        console.log('res', res4)
                        wx.navigateTo({
                          url: '../buy_suc/buy_suc?session=' + session + '&productId=' + productId + '&orderId=' + res.data.data[0],
                        })

                      },
                      'fail': function (res) {
                      },
                      'complete':function(){
getDataFlag=false;
                      },
                    })
                  }
                  else {
                    wx.showModal({
                      title: '提示信息',
                      content: res.data.msg,
                      cancelText: "取消",
                      cancelColor: '',
                      confirmText: '确认',
                    })
                  }
                }
              })
            }
          })
        }
        else {
          console.log(res.data.status)
          if (res.data.status == 4003) {
            wx.showModal({
              title: '提示',
              content: '很抱歉,您所购买的区域余票不足,是否接受系统自动派票',
              cancelText: "重选",
              cancelColor: '',
              confirmText: '接受',
              confirmColor: '',
              success: function (res) {
                if (res.confirm) {
                  console.log(rest)
                  that.setData({
                    checked: true
                  })
                  that.submit();
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              },
              complete: function () {
                that.setData({
                  checked: false
                })
                rest = 0;
              }
            })
            return;
          }
          if (res.data.status == 4004) {
            wx.showModal({
              title: '',
              content: '很抱歉,很抱歉目前门票已售空,您可以关注此次活动公众号并转发海报赚取芳菲币,参与线上活动',
              cancelText: "关注",
              cancelColor: '',
              confirmText: '返回活动',
              confirmColor: '',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
            return;
          }
          if (res.data.status == 4005) {
            wx.showModal({
              title: '',
              content: '很抱歉,目前余票仅剩' + res.data.msg+'张,是否继续购买',
              cancelText: "返回活动",
              cancelColor: '',
              confirmText: '购买',
              confirmColor: '',
              success: function (res5) {
                if (res5.confirm) {
                 that.setData({
                   count: res.data.msg
                 })
                 that.submit();
                } else if (res5.cancel) {
                  wx.navigateBack({
                    
                  })
                }
              }
            })
            return;
          }
          else {
            wx.showModal({
              title: '提示信息',
              content: res.data.msg,
              showCancel:true,
              cancelText: "取消",
              cancelColor: '',
              confirmText: '确认',
              confirmColor: '',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }

        }


      },
      complete: function () {
        getDataFlag = false;
      },

    })
  },
  check: function () {
    this.setData({
      checked: !this.data.checked
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var mobile = wx.getStorageSync('mobile')
    if (!mobile==false)
{
      this.setData({
        phone: mobile
      })
}
    console.log(options)
    wx.setNavigationBarTitle({
      title: options.title
    })
    var that = this;
    wx.request({
      url: app.globalData.rootUrl + '/api/product/get/',
      data: {
        id: options.id,
      },
      success: function (res) {
        var sellQtynum;
        for (let [index, elem] of res.data.data[0].sections.entries()) {
          if (elem.sellQty != 0)
            sellQtynum = index
          console.log('sellQtynum' + sellQtynum)
          break;
        }
        console.log('sellQtynum' + sellQtynum)
        that.setData({
          seat: res.data.data[0].sections,
          productId: options.id,
          selnum: sellQtynum,
        })
        that.setData({
          price: that.data.seat[0].sellPrice,
        })
        console.log("后台用户会话", res.data)
      }
    })
    that.setData({
      checkButton: wx.getStorageSync('checkButton')
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
onShow:function(){
 // this.onLoad()
},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我已加入活动，邀请您一起参加',
      path: 'pages/index/index?productId=' + this.data.productId + '&refId=' + wx.getStorageSync('memberId'),
      imageUrl: '../image/shareimg.jpg'
    }
  }
})